package controllers;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import admin.controllers.EditDealServlet;
import models.GeoModel;

import data.DealData;
import data.GeoData;

@SuppressWarnings("serial")
public class HomeServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(EditDealServlet.class
			.getName());

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		try {
			response.setCharacterEncoding("UTF-8");
			int page = 1;
			try {
				page = Integer.parseInt((String) request.getParameter("page"));
			} catch (Exception e) {
				page = 1;
			}
			Cookie cookies[] = request.getCookies();
			GeoData geoData = new GeoData();
			GeoModel currentCity = geoData.getFirstCity();
			String cityId = currentCity.getGeoId();
			String cityAlias = currentCity.getAlias();
			if (cookies != null) {
				for (int i = 0; i < cookies.length; i++) {
					if (cookies[i].getName().equals("city")) {
						cityAlias = cookies[i].getValue();
						break;
					}
				}
			} else {
				Cookie cookie = new Cookie("city", cityAlias);
				cookie.setMaxAge(60 * 60 * 24);
				response.addCookie(cookie);
			}
			DealData dealData = new DealData();
			dealData.setPage(page);
			dealData.getByCity(cityId);
			request.setAttribute("city", currentCity.getAlias());
			request.setAttribute("recentCategory", null);
			request.setAttribute("dealData", dealData);
			request.setAttribute("url", request.getRequestURL().toString());
			request.getRequestDispatcher("/pages/home_page.jsp").forward(
					request, response);
		} catch (ServletException e) {
			System.out.println("Error when connect home page !");
			log.warning("Error when redirect list deal !");
			log.warning(e.toString());
			e.printStackTrace();
			request.getRequestDispatcher("/pages/error.jsp").forward(request,
					response);
		}
	}
}
